import json
import datetime

class AuthManager:
    def __get_config(self):
        with open("auth.json", "r") as f:
            config = json.load(f)
            return config

    def __is_expired(self, time: str):
        t = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
        return datetime.datetime.now() > t
        
    def auth_key(self, key):
        config = self.__get_config()
        for keyinfo in config["keylist"]:
            if keyinfo['key'] == key:
                if self.__is_expired(keyinfo['expire']):
                    raise Exception(f"已过期, 请联系管理员续费: {keyinfo}")
                else:
                    return True
        raise Exception(f"key认证失败: {key}")

    def auth_white(self, ip):
        config = self.__get_config()
        for keyinfo in config["whitelist"]:
            if keyinfo['key'] == ip:
                if self.__is_expired(keyinfo['expire']):
                    raise Exception(f"已过期, 请联系管理员续费: {keyinfo}")
                else:
                    return True
        raise Exception(f"ip认证失败: {ip}")